package entities.controllers;

import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import utils.Utils;
import entities.kinds.User;
import entities.pmf.PMF;

public class Users {
	static final PersistenceManager pm = PMF.getInstance().getPersistenceManager();

	public static String register(String login, String password) {
		String loginEnc = "";
		try {
			User user = new User(Utils.SHA256(Utils.MD5(login)), Utils.SHA256(Utils.MD5(password)));
			pm.makePersistent(user);
			loginEnc = user.getLogin();
		} catch (Exception e) {
			System.out.println("user add err:" + e);
		}
		return loginEnc;
	}

	public static boolean loginSuccessful(String login, String password) {
		Query q = pm.newQuery(User.class);
		q.setFilter("login == login_ && password == password_");
		q.declareParameters("String login_, String password_");
		@SuppressWarnings("unchecked")
		List<User> res = (List<User>) q.execute(Utils.SHA256(Utils.MD5(login)),
				Utils.SHA256(Utils.MD5(password)));
		if (!res.isEmpty())
			if (res.size() == 1)
				return true;
		return false;
	}

	public static boolean loginAvailable(String login) {
		Query q = pm.newQuery(User.class);
		q.setFilter("login == login_");
		q.declareParameters("String login_");
		@SuppressWarnings("unchecked")
		List<User> res = (List<User>) q.execute(Utils.SHA256(Utils.MD5(login)));
		if (!res.isEmpty())
			return false;
		return true;
	}

	public static boolean cookieLoginSuccessful(String login) {
		Query q = pm.newQuery(User.class);
		q.setFilter("login == login_");
		q.declareParameters("String login_");
		@SuppressWarnings("unchecked")
		List<User> res = (List<User>) q.execute(login);
		if (!res.isEmpty())
			if (res.size() == 1)
				return true;
		return false;
	}

}
